using UniversalAdminSystem.Application.SystemSettings.DTOs;
using UniversalAdminSystem.Application.SystemSettings.Interfaces;
using UniversalAdminSystem.Domian.SystemSettings.Aggregates;
using UniversalAdminSystem.Domian.Core.Interfaces;
using UniversalAdminSystem.Application.Common.Results;
using UniversalAdminSystem.Domian.SystemSettings.ValueObjects;
using UniversalAdminSystem.Application.Common.Interfaces;

namespace UniversalAdminSystem.Application.SystemSettings.Services;

public class SystemSettingAppService : ISystemSettingAppService
{
    private readonly IRepository<SystemSetting> _settingRepository;
    private readonly IUnitOfWork _unitOfWork;

    public SystemSettingAppService(
        IRepository<SystemSetting> settingRepository,
        IUnitOfWork unitOfWork)
    {
        _settingRepository = settingRepository;
        _unitOfWork = unitOfWork;
    }

    public async Task<Result<IEnumerable<SystemSettingDto>>> GetAllSettingsAsync()
    {
        try
        {
            var settings = await _settingRepository.GetAllAsync();
            var settingDtos = settings.Select(MapToDto);
            return Result<IEnumerable<SystemSettingDto>>.Success(settingDtos);
        }
        catch (Exception ex)
        {
            return Result<IEnumerable<SystemSettingDto>>.Failure($"获取系统设置失败: {ex.Message}");
        }
    }

    public async Task<Result<SystemSettingDto?>> GetSettingByKeyAsync(string key)
    {
        try
        {
            var setting = (await _settingRepository.GetAllAsync()).FirstOrDefault(s => s.Key.Value == key);
            if (setting == null)
            {
                return Result<SystemSettingDto?>.Failure("设置不存在");
            }

            return Result<SystemSettingDto?>.Success(MapToDto(setting));
        }
        catch (Exception ex)
        {
            return Result<SystemSettingDto?>.Failure($"获取系统设置失败: {ex.Message}");
        }
    }

    public async Task<Result<IEnumerable<SystemSettingDto>>> GetSettingsByGroupAsync(string group)
    {
        try
        {
            var settings = await _settingRepository.GetAllAsync();
            var groupSettings = settings.Where(s => s.Key.Value.StartsWith(group));
            var settingDtos = groupSettings.Select(MapToDto);
            return Result<IEnumerable<SystemSettingDto>>.Success(settingDtos);
        }
        catch (Exception ex)
        {
            return Result<IEnumerable<SystemSettingDto>>.Failure($"获取系统设置失败: {ex.Message}");
        }
    }

    public async Task<Result<SystemSettingDto>> CreateSettingAsync(SystemSettingCreateDto createDto)
    {
        try
        {
            await _unitOfWork.BeginTransactionAsync();

            var setting = SystemSetting.Create(
                SettingKey.Create(createDto.Key),
                SettingValue.Create(createDto.Value),
                SettingDescription.Create(createDto.Description ?? "")
            );

            var savedSetting = await _settingRepository.AddAsync(setting);
            await _unitOfWork.CommitAsync();

            return Result<SystemSettingDto>.Success(MapToDto(savedSetting));
        }
        catch (Exception ex)
        {
            await _unitOfWork.RollbackAsync();
            return Result<SystemSettingDto>.Failure($"创建系统设置失败: {ex.Message}");
        }
    }

    public async Task<Result<SystemSettingDto>> UpdateSettingAsync(Guid id, SystemSettingUpdateDto updateDto)
    {
        try
        {
            await _unitOfWork.BeginTransactionAsync();

            var setting = await _settingRepository.GetByGuidAsync(id);
            if (setting == null)
            {
                return Result<SystemSettingDto>.Failure("设置不存在");
            }

            setting.UpdateValue(SettingValue.Create(updateDto.Value));

            await _settingRepository.Update(setting);
            await _unitOfWork.CommitAsync();

            return Result<SystemSettingDto>.Success(MapToDto(setting));
        }
        catch (Exception ex)
        {
            await _unitOfWork.RollbackAsync();
            return Result<SystemSettingDto>.Failure($"更新系统设置失败: {ex.Message}");
        }
    }

    public async Task<Result> DeleteSettingAsync(Guid id)
    {
        try
        {
            await _unitOfWork.BeginTransactionAsync();

            var setting = await _settingRepository.GetByGuidAsync(id);
            if (setting == null)
            {
                return Result.Failure("设置不存在");
            }

            await _settingRepository.RemoveAsync(id);
            await _unitOfWork.CommitAsync();

            return Result.Success("删除成功");
        }
        catch (Exception ex)
        {
            await _unitOfWork.RollbackAsync();
            return Result.Failure($"删除系统设置失败: {ex.Message}");
        }
    }

    private static SystemSettingDto MapToDto(SystemSetting s) => new(
        s.Id,
        s.Key.Value,
        s.Value.Value,
        s.Description?.Value,
        s.Group,
        s.CreateTime,
        s.UpdateTime
    );
} 